package com.example.demo.util;


import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.context.annotation.Configuration;

import java.net.URI;

@Configuration
public class HttpClientUtil {

    public static String  doGet(String url){
        String resultString = null;
        try{
            // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建Get请求
            HttpGet httpGet = new HttpGet(uri);
            // 响应模型
            CloseableHttpResponse response = null;
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
            .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
            .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
            .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
            .setRedirectsEnabled(true).build();

            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            resultString = EntityUtils.toString(responseEntity);
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
//                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }

            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();

            }

            return resultString;
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultString;
    }





}
